package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * FastDfs接口
 *  上传：要写  - 调用工具类 - Post
 *      前端：type="file" ,multipart/form-data
 *      后端：MultipartFile对象 - @RequestPart
 *  删除：要写  - 调用工具类 - Delete
 *      前端：/dept./add?path=/group1/M00/01/B0/CgAIC2MdpwuAJ9IdAABiwl7Ttcc071.jpg
 *      后端：@RequestParam
 *  更新：不写 - 先删除 再上传
 *  查询：不写 - http://123.207.27.208//group1/M00/01/B0/CgAIC2MdpwuAJ9IdAABiwl7Ttcc071.jpg
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传接口：
     * ElementUi - 提供的上传组件，上传组件中默认name="file"
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart("file")MultipartFile file){
        try {
            //获取原始文件名
            String oName = file.getOriginalFilename(); // xxx.jpg
            String extName = oName.substring(oName.lastIndexOf(".") + 1);//jpg
            //上传成功之后返回的文件名
            String fileName = FastDfsUtils.upload(file.getBytes(), extName);
            //将文件名设置到AjaxResult并返回给前端
            return AjaxResult.me().setResultObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }


    /**
     * 文件删除接口
     *  约定好：前端传递的时候要以
     *  delete   fastDfs?path=/group1/M00/01/B0/CgAIC2MdpwuAJ9IdAABiwl7Ttcc071.jpg
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path")String path){
        try {
            String temPath = path.substring(1); //  group1/M00/01/B0/CgAIC2MdpwuAJ9IdAABiwl7Ttcc071.jpg
            //获取第一个/的位置
            int index = temPath.indexOf("/");
            String groupName = temPath.substring(0,index); // group1
            String fileName = temPath.substring(index+1);
            FastDfsUtils.delete(groupName,fileName);
            //将文件名设置到AjaxResult并返回给前端
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
